package com.icarus.quartz.controller;

import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.icarus.quartz.entity.QuartzJob;
import com.icarus.quartz.service.QuartzJobService;

@Controller
@RequestMapping("/quartzJob")
public class QuartzJobController {
	private Log logger = LogFactory.getLog(QuartzJobController.class);

	@Autowired
	private QuartzJobService quartzJobService;

	@RequestMapping("/index")
	public String index(Model model) {
		try {
			List<QuartzJob> quartzJobs = quartzJobService.getList();
			model.addAttribute("quartzJobs", quartzJobs);
			return "/quartz/index";
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/500";
		}
	}

	@RequestMapping("/add")
	public String add(Model model) {
		try {
			QuartzJob quartzJob = new QuartzJob();
			model.addAttribute("quartzJob", quartzJob);
			return "/quartz/edit";
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/500";
		}
	}

	@RequestMapping("/save")
	public String save(QuartzJob quartzJob) {
		try {
			quartzJobService.add(quartzJob);
			return "/common/200";
		} catch (Exception e) {
			e.printStackTrace();
			return "/error/500";
		}
	}

	@RequestMapping("/getList")
	public String getList() {
		JSONObject resultJson = new JSONObject();
		try {
			resultJson.put("success", true);
			List<QuartzJob> jobs = quartzJobService.getList();
			resultJson.put("message", "操作成功!");
			resultJson.put("datas", jobs);
		} catch (Exception e) {
			resultJson.put("success", false);
			resultJson.put("message", "操作失败!");
			logger.error("任务保存异常！", e);
		}
		return resultJson.toString();
	}

	@RequestMapping("/init")
	@ResponseBody
	public JSONObject init() {
		JSONObject resultJson = new JSONObject();
		try {
			resultJson.put("success", true);
			quartzJobService.init();
			resultJson.put("message", "操作成功!");
		} catch (Exception e) {
			resultJson.put("success", false);
			resultJson.put("message", "操作失败!");
			logger.error("任务初始化异常！", e);
		}
		return resultJson;
	}

}
